<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form ref="form" :model="form" label-width="80px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect ref="yongdianqiye" 
              :optionlist="yonghulist" 
              :valuekey="{name:'name',value:'id'}" 
              @changeselect="changeqite" 
              :defaultvalue="companyId"
              ></FilterSelect>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="能源类型">
              <el-select v-model="energyTypeId" placeholder="请选择能源类型"  size="small" style="width: 100%" @change="$forceUpdate()">
                <el-option v-for="(item,index) in leixinglist" :key="index" :label="item.name" :value="item.code" class="option"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="模型名称">
              <el-input v-model="attritionModelName"  placeholder="请输入损耗模型名称" size="small" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9" style="text-align: right;">
            <el-form-item label="">
              <el-button size="small" @click="chongzhi">重 置</el-button>
              <el-button size="small" type="primary" @click="getdatalist()">查 询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <div class="left">
          <span class="spans">用电企业</span>
          <span class="spans">
            <el-select v-model="companyId" placeholder="请选择用电单位"  size="small" style="width: 200px;" @change="changeqite">
              <el-option v-for="(item,index) in yonghulist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
            </el-select>
          </span>
          <span class="spans">能源类型/介质</span>
          <span class="spans">
            <el-select v-model="energyTypeId" placeholder="请选择能源类型"  size="small" style="width: 200px;" @change="$forceUpdate()">
               <el-option v-for="(item,index) in leixinglist" :key="index" :label="item.name" :value="item.code" class="option"></el-option>
            </el-select>
          </span>
          <span class="spans">损耗模型名称</span>
          <span class="spans">
            <el-input v-model="attritionModelName"  placeholder="请输入损耗模型名称" size="small" style="width: 200px;"></el-input>
          </span>
        </div>
        <div>
          <el-button size="small" @click="chongzhi">重 置</el-button>
          <el-button size="small" type="primary" @click="getdatalist()">查 询</el-button>
        </div> -->
    </div>
    <div class="borderbox">
      <div class="titlebutt">
        <span>损耗模型配置</span>
        <span style="display: flex;">
          <el-button size="small" type="primary" @click="dialogVisible=true">新 增</el-button>
          <TopTooltip @shuaxin="shuaxin" @command="command"></TopTooltip>
         </span>
      </div>
      <div class="tables">
        <TableColumn
        ref="tabledata"
        :tableData="tableData" 
        :tableConfig="tableConfig" 
        :issize="issize">
        <el-table-column
        label="损耗级别">
        <template #default="{row}">
          <span>{{ dengjilist.filter(ele=>ele.value==row.attritionLevel)[0]?.text }}</span>
        </template>
      </el-table-column>
        <el-table-column 
        label="能源类型/介质">
        <template #default="{row}">
          <span>{{ leixinglist.filter(ele=>ele.code==row.energyTypeId)[0]?.name }}</span>
        </template>
        </el-table-column>
        <el-table-column
            prop="address"
            label="操作"
            align="center"
            width="150">
            <template #default="{row}">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <i @click="update(row)" class="el-icon-edit" style="color:#1a90fe ;margin-right: 20px; cursor: pointer;"></i>
               </el-tooltip>
               <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i @click="dellist(row)" class="el-icon-delete" style="color: red;cursor: pointer;"></i>
               </el-tooltip>
            </template>
          </el-table-column>
        </TableColumn>
        <!-- 底部分页 -->
        <div class="fenye">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page.sync="pageobj.pageNo"
            :page-size="15"
            @current-change="getdatalist"
            :total="+totalCount">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <div>
      <el-dialog
        :title="form.id?'损耗模型编辑':'损耗模型新增'"
        :visible.sync="dialogVisible"
        width="45%">
        <div>
          <el-form ref="form" :model="form" label-width="120px" :rules="rulesform">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用电单位" prop="companyId">
                  <el-select v-model="form.companyId" placeholder="请选择用电单位"  size="small" style="width:100%;">
                    <el-option v-for="(item,index) in yonghulist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="能源类型/介质" prop="energyTypeId">
                  <el-select v-model="form.energyTypeId" placeholder="请选择能源类型"  size="small" style="width:100%;" @change="$forceUpdate()">
                    <el-option v-for="(item,index) in leixinglist" :key="index" :label="item.name" :value="item.code" class="option"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row >
              <el-col :span="12">
                <el-form-item label="损耗级别" prop="attritionLevel">
                  <el-select v-model="form.attritionLevel" placeholder="请选择损耗级别"  size="small" style="width:100%;" @change="changjibie">
                    <el-option v-for="(item,index) in dengjilist" :key="index" :label="item.text" :value="item.value" class="option"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上级损耗模型" prop="parentAttritionModel">
                  <el-input v-model="form.parentAttritionModel" placeholder="请输入上级损耗模型" size="small"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row >
              <el-col :span="12">
                <el-form-item label="上级计量点" prop="upMeterPoints">
                  <el-select  v-model="form.upMeterPoints" placeholder="选择上级计量点" size="small"  style="width: 100%;" ref="selectReport">
                        <el-option class="option" :label="upMeterPoints.name" :value="form.upMeterPoints" style="height: auto">
                              <el-tree ref="tree" :props="props" :highlight-current="true" :load="loadNodedevice" lazy
                              @node-click="handleNodeClick">
                              <template slot-scope="{ node, data }">
                                <span :style="{
                                  // cursor: data.className == 'AirconditionMain' || data.className == 'CoolingTower' || data.className == 'Boiler' || data.className == 'FreezePump' ||  
                                  // data.className == 'CoolingPump' || data.className == 'DraughtFanCoiler' || data.className == 'NewDraughtFan' || data.className == 'Lighting' ||
                                  // data.className == 'Socket' ||data.className == 'Elevator' ||data.className == 'Pump' ||data.className == 'ExhaustFan' ||data.className == 'ElectricCalorifier' ||
                                  // data.className == 'SpeElectricDevice' || data.className == 'ProElectricDevice' || data.className == 'LightingSocket' || data.className == 'RollingMillDevice' ||
                                  // data.className == 'Pipeline' || data.className == 'Heatingpump' || data.className == 'Watersuppump' || data.className == 'EcmEquip' ? 'pointer' : 'no-drop',
                                    fontSize: '14px', color: '#606266'
                                  }">
                                  {{ node.label }}</span>
                              </template>
                            </el-tree>
                          </el-option>
                      </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="下级计量点" prop="lowMeterPoints">
                  <el-select  v-model="form.lowMeterPoints" placeholder="选择下级计量点" size="small"  style="width: 100%;" ref="lowMeterPoints">
                        <el-option class="option" :label="lowMeterPoints.name" :value="form.lowMeterPoints" style="height: auto">
                              <el-tree ref="tree" :props="props" :highlight-current="true" :load="loadNodedevice" lazy
                              @node-click="handleNodeClicklow">
                              <template slot-scope="{ node, data }">
                                <span :style="{
                                  // cursor: data.className == 'AirconditionMain' || data.className == 'CoolingTower' || data.className == 'Boiler' || data.className == 'FreezePump' ||  
                                  // data.className == 'CoolingPump' || data.className == 'DraughtFanCoiler' || data.className == 'NewDraughtFan' || data.className == 'Lighting' ||
                                  // data.className == 'Socket' ||data.className == 'Elevator' ||data.className == 'Pump' ||data.className == 'ExhaustFan' ||data.className == 'ElectricCalorifier' ||
                                  // data.className == 'SpeElectricDevice' || data.className == 'ProElectricDevice' || data.className == 'LightingSocket' || data.className == 'RollingMillDevice' ||
                                  // data.className == 'Pipeline' || data.className == 'Heatingpump' || data.className == 'Watersuppump' || data.className == 'EcmEquip' ? 'pointer' : 'no-drop',
                                  fontSize: '14px', color: '#606266'
                                  }">
                                  {{ node.label }}</span>
                              </template>
                            </el-tree>
                          </el-option>
                      </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="损耗模型名称" prop="attritionModelName">
                  <el-input v-model="form.attritionModelName" placeholder="请输入损耗模型名称" size="small" style="width:100%;"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="quxiao">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import FilterSelect from '@/components/FilterSelect'
import TopTooltip from '@/components/TopTooltip/index.vue'
import { getgenjiedianapi, getzijidianapi } from '@/api/monitor'
import {getzidianxialaapi} from '@/api/guidelines'
import TableColumn from '@/components/Table/index.vue'
import {getyongdianlistapi} from '@/api/energy-consumption/Basic-information/medium'
import {getnengyuantypeapi} from '@/api/energy-consumption/Basic-information/gateway'
import {gettablelistapi,getguanxiapi,postaddmodelapi,postdelmodelapi,postupdatemodelapi} from '@/api/energy-consumption/Basic-analysis/Model-Loss'
export default {
  name: 'CallPoliceIndex',
  components: {
    FilterSelect,
    TableColumn,
    TopTooltip
  },
  data() {
    return {
      form:{},
      companyId: '',
      energyTypeId: '',
      attritionModelName:'',
      dialogVisible:false,
      leixinglist: [],
      yonghulist:[],
      issize: 'medium',
      tableData: [],
      tableConfig: [
        { label: '序号', type: 'index', center: 'center', width: '100' },
        { label: '用电单位', prop: 'companyName',  },
        // { label: '能源类型/介质', prop: 'energyTypeName',},
        { label: '损耗模型名称', prop: 'attritionModelName',},
        // { label: '损耗级别', prop: 'dataSourcesName',   },
        { label: '上级计量点', prop: 'upMeterPointsName',   },
        { label: '下级计量点', prop: 'lowMeterPointsName',   },
      ],
      totalCount: '',
      pageobj: {
        pageNo: 0,
        pageSize:15
      },
      props:{label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      upMeterPoints:{name:'',id:''},
      lowMeterPoints: { name: '', id: '' },
      dengjilist: [],
      rulesform: {
        companyId:[{ required: true, message: '请选择用电单位', trigger: 'change' },],
        energyTypeId:[{ required: true, message: '请选择能源类型/介质', trigger: 'change' },],
        attritionLevel:[{ required: true, message: '请选择损耗级别', trigger: 'change' },],
        parentAttritionModel:[{ required: true, message: '请输入上级损耗模型', trigger: 'blur' },],
        upMeterPoints:[{ required: true, message: '请选择上级计量点', trigger: 'change' },],
        lowMeterPoints:[{ required: true, message: '请选择下级计量点', trigger: 'change' },],
        attritionModelName:[{ required: true, message: '请输入损耗模型名称', trigger: 'blur' },],
      }
    };
  },

  async mounted() {
    // 获取用电单位
    const {data:{list}} = await getyongdianlistapi()
    this.yonghulist = list
    const companyId = localStorage.getItem('companyId')
    this.$set(this,'companyId',companyId?+companyId:'')
    // 获取能源类型并筛选
    const res = await getnengyuantypeapi()
    this.leixinglist = res.data.list
    // 获取能源类型并筛选
    const dengji = await getzidianxialaapi({ dictType: 'attritionLevel' })
    this.dengjilist = dengji.data.list
    this.getdatalist()
  },

  methods: {
    changeqite(val) {
      this.$set(this,'companyId',val)
      localStorage.setItem('companyId', val)
    },
    // 弹窗确定
    async submit() {
      await this.$refs.form.validate()
      try {
        this.form.id ? await postupdatemodelapi({ ...this.form }) :
        await postaddmodelapi({ ...this.form})
        this.$message.success(`${this.form.id ?'修改':'新增'}成功`)
      } catch (error) {
        this.$message.warning('操作失败')
      }
      this.quxiao()
      this.getdatalist()
    },
    // 修改
    update(row) {
      this.dialogVisible=true
      this.form = { ...row }
      this.$set(this.upMeterPoints,'name',row.upMeterPointsName)
      this.$set(this.lowMeterPoints,'name',row.lowMeterPointsName)
      this.changjibie(row.attritionLevel)
    },
    // 重置
    chongzhi() {
      this.companyId = ''
      this.energyTypeId = ''
      this.attritionModelName = ''
      this.getdatalist()
    },
    // 删除
    dellist(row) {
      this.$confirm('此操作将永久删除该配置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await postdelmodelapi({ id: row.id }).then(res => {
            this.$message({
              type: res.code == 200 ? 'success' : 'warning',
              message:res.code == 200 ?'删除成功':res.message
            })
          })
          this.getdatalist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取表格数据
    async getdatalist() {
      this.$refs.tabledata.loading=true
      const { data: { list,totalCount } } = await gettablelistapi({
         attritionModelName: this.attritionModelName,
        pageNo: this.pageobj.pageNo - 1,companyId:this.companyId,
        pageSize: this.pageobj.pageSize,energyTypeId:this.energyTypeId,
      })
      this.tableData = list
      this.totalCount=totalCount
      this.$refs.tabledata.loading=false
    },
    // 损耗级别下拉选择
    async changjibie(val) {
      const {data} = await getguanxiapi({ attritionLevel: val, companyId: this.form.companyId, energyTypeId: this.form.energyTypeId })
      this.$set(this.form,'parentAttritionModel', data.entity?data.entity.parentAttritionModel:'')
    },
    // 上级树点击
    handleNodeClick(val) {
      // if(val.className == 'AirconditionMain' || val.className == 'CoolingTower' || val.className == 'Boiler' || val.className == 'FreezePump' ||  
      //    val.className == 'CoolingPump' || val.className == 'DraughtFanCoiler' || val.className == 'NewDraughtFan' || val.className == 'Lighting' ||
      //    val.className == 'Socket' ||val.className == 'Elevator' ||val.className == 'Pump' ||val.className == 'ExhaustFan' ||val.className == 'ElectricCalorifier' ||
      //    val.className == 'SpeElectricDevice' || val.className == 'ProElectricDevice' || val.className == 'LightingSocket' || val.className == 'RollingMillDevice' ||
      //   val.className == 'Pipeline' || val.className == 'Heatingpump' || val.className == 'Watersuppump' || val.className == 'EcmEquip') {
          this.$set(this.upMeterPoints,'name',val.name)
          this.$set(this.form, 'upMeterPoints', val.id)
          this.$refs.selectReport.blur()
      // }
    },
    // 下级树点击
    handleNodeClicklow(val) {
      // if(val.className == 'AirconditionMain' || val.className == 'CoolingTower' || val.className == 'Boiler' || val.className == 'FreezePump' ||  
      //    val.className == 'CoolingPump' || val.className == 'DraughtFanCoiler' || val.className == 'NewDraughtFan' || val.className == 'Lighting' ||
      //    val.className == 'Socket' ||val.className == 'Elevator' ||val.className == 'Pump' ||val.className == 'ExhaustFan' ||val.className == 'ElectricCalorifier' ||
      //    val.className == 'SpeElectricDevice' || val.className == 'ProElectricDevice' || val.className == 'LightingSocket' || val.className == 'RollingMillDevice' ||
      //    val.className == 'Pipeline' || val.className == 'Heatingpump' || val.className == 'Watersuppump' || val.className == 'EcmEquip') {
          this.$set(this.lowMeterPoints,'name',val.name)
          this.$set(this.form, 'lowMeterPoints', val.id)
          this.$refs.lowMeterPoints.blur()
        //  }
    },
    quxiao() {
      this.$refs.form.resetFields()
      this.dialogVisible = false
      this.form.id = ''
      this.upMeterPoints={name:'',id:''}
      this.lowMeterPoints={ name: '', id: '' }
    },
       // 调节表格密度
  command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 列表刷新
    shuaxin() {
      this.getdatalist()
      this.$message.success('列表刷新成功')
    },
    // 设备树懒加载
    async loadNodedevice (node, resolve) {
      // const res = await getgenjiedianapi({ treeModel: 'MbmDeviceManageTree' })
      const res = await getgenjiedianapi({ treeModel: 'ENERGY_SET_TREE' })
      // const res = await getzijidianapi()
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) { // 初始的级数（最顶层）
        return resolve(ress.data.list) // 最顶层数据渲染为region
      }
      if (node.level === 0) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 1) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 2) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 3) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 4) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 5) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
  },
};
</script>

<style scoped>
.option{
  padding-left: 10px;
}
.bigbox{
  height: 100%;
  padding: 10px;
  .topbox{
    height: 80px;
    padding: 20px;
    background-color: #fff;
    margin-bottom: 10px;
  }
  .borderbox{
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .titlebutt{
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    .tables{
      height: 90%;
      .fenye{
        text-align: right;
        margin-top: 10px;
      }
    }
  }
}
::v-deep .el-dialog__footer{
  text-align: center;
  .el-button{
    width: 60px;
    height: 30px;
  }
}
::v-deep .el-form-item__error{
  padding: 0;
}
::v-deep .el-row{
  margin-bottom: 10px;
}
</style>